﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using PMSWenLvTing.BLL;
using PMSWenLvTing.Model;
using PMSWenLvTing.Model.JiuDian;
using PMSWenLvTing.Utility;
using Utility;

namespace PMSWenLvTing.Controllers
{
    public class LoginController : Controller
    {
        MainBLL bll = new MainBLL();

        //登录方法
        public ActionResult Login()
        {
            return View();
        }

        //登录处理方法
        public ActionResult LoginP()
        {
            //酒店端 测试代码
            //List<yonghu_jiudian> lisjd_ceshi = bll.Get_yonghu_jiudian(" zhanghao='13807538794' AND zhuangtai=1 ");
            //Session["yonghuinfo"] = lisjd_ceshi.First();
            //Session["menu_jdname"] = "小刘测试酒店";
            //Session["menu_yhname"] = "小刘";
            //bll.Get_jiudian(new List<int>() { 1,2,3,4 }, true);
            //return Json(CommonHelper.Self_GetRes(1, "登录成功！", false, "/jiudian/JDDaiTianBao"));

            //文旅厅端 测试代码
            List<yonghu_wenlvting> lisjd_ceshi = bll.Get_yonghu_wenlvting(" zhanghao='admin' AND zhuangtai=1 ");
            Session["yonghuinfo"] = lisjd_ceshi.First();
            Session["menu_jdname"] = "文旅厅";
            Session["menu_yhname"] = "小刘";
            bll.Get_jiudian_aid(new List<int>() { 2206, 2207, 2208, 2209, 2210, 2215, 2220, 2224, 2225, 2226, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235 }, true);
            return Json(CommonHelper.Self_GetRes(1, "登录成功！", false, "/wenlvting/WLTDataCenter"));



            string name = Request["name"];
            string imgyzm = Request["imgyzm"];
            string dxyzm = Request["dxyzm"];

            #region 检查数据是否有效
            if (string.IsNullOrEmpty(name))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入电话号码！", false, ""));
            }
            else
            {
                if (Regex.IsMatch(name, @"^1[3456789]\d{9}$") == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "无效电话号码！", false, ""));
                }
                if (Session["dxphone"] != null && string.IsNullOrEmpty(Session["dxphone"].ToString()) == false && Self_CheckImgYZM("dxphone", name) == false)
                {
                    //更换了电话号码，需要重新发送短信
                    Session["dxyzm"] = "";
                    return Json(CommonHelper.Self_GetRes(-1, "请重新发送短信验证码！", false, ""));
                }
            }
            if (string.IsNullOrEmpty(imgyzm))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入图片验证码！", false, ""));
            }
            else
            {
                if (Self_CheckImgYZM("checkcode", imgyzm) == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "图片验证码错误！", false, ""));
                }
            }
            if (string.IsNullOrEmpty(dxyzm))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入短信验证码！", false, ""));
            }
            else
            {
                if (Self_CheckImgYZM("dxyzm", dxyzm) == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "短信验证码错误！", false, ""));
                }
            }
            #endregion

            #region 账号是否存在
            string whereStr = " zhanghao='" + name + "' AND zhuangtai=1 ";
            DTO_Res msg = new DTO_Res();
            //酒店用户
            List<yonghu_jiudian> lisjd = bll.Get_yonghu_jiudian(whereStr);

            if (lisjd != null && lisjd.Count == 1)
            {
                yonghu_jiudian LModel = lisjd.First();
                msg = CommonHelper.Self_GetRes(1, "登录成功！", false, "/main/rimingxi");
                Session["yonghuinfo"] = LModel;
                Session["menu_jdname"] = "小刘测试酒店";
                Session["menu_yhname"] = LModel.xingming;
                bll.Get_jiudian(JsonConvert.DeserializeObject<List<int>>(LModel.jdid_json), true);
                return Json(msg);
            }

            //文旅厅用户
            List<yonghu_wenlvting> liswlt = bll.Get_yonghu_wenlvting(whereStr);
            if (lisjd != null && lisjd.Count == 1)
            {
                yonghu_wenlvting LModel = liswlt.First();
                msg = CommonHelper.Self_GetRes(1, "登录成功！", false, "/main/rimingxi");
                Session["yonghuinfo"] = LModel;
                return Json(msg);
            }

            #endregion

            msg = CommonHelper.Self_GetRes(-1, "密码或用户名错误！", false, "");
            return Json(msg);
        }

        //生成图片验证码
        public ActionResult GetYanZhengMa()
        {
            string chkCode = string.Empty;
            int ix, iy;
            ix = 100;
            iy = 42;
            //颜色列表，用于验证码、噪线、噪点 
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表，用于验证码 
            string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "MingLiU", "Arial" };
            //验证码的字符集，去掉了一些容易混淆的字符 
            char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd = new Random();
            //生成验证码字符串 
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            Bitmap bmp = new Bitmap(ix, iy);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            //画噪线 
            for (int i = 0; i < 10; i++)
            {
                int x1 = rnd.Next(ix);
                int y1 = rnd.Next(iy);
                int x2 = rnd.Next(ix);
                int y2 = rnd.Next(iy);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串 
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, 22, FontStyle.Bold);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 22 + 2, (float)2);
            }
            //画噪点 
            for (int i = 0; i < 50; i++)
            {
                int x = rnd.Next(bmp.Width);
                int y = rnd.Next(bmp.Height);
                Color clr = color[rnd.Next(color.Length)];
                bmp.SetPixel(x, y, clr);
            }
            //将验证码写入SESSION
            Session["checkcode"] = chkCode.ToLower();
            //清除该页输出缓存，设置该页无缓存 
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");
            //将验证码图片写入内存流，并将其以 "image/Png" 格式输出  
            MemoryStream ms = new MemoryStream();
            try
            {
                bmp.Save(ms, ImageFormat.Png);
                Response.ClearContent();
                Response.ContentType = "image/Png";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                //显式释放资源 
                bmp.Dispose();
                g.Dispose();

            }
            return null;
        }

        //发送短信验证码
        public ActionResult SendDuanXin()
        {
            string name = Request["name"];
            string imgyzm = Request["imgyzm"];

            #region 检查数据是否有效
            if (string.IsNullOrEmpty(name))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入电话号码", false, ""));
            }
            else
            {
                if (Regex.IsMatch(name, @"^1[3456789]\d{9}$") == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "无效电话号码！", false, ""));
                }
            }
            if (string.IsNullOrEmpty(imgyzm))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入图片验证码", false, ""));
            }
            else
            {
                if (Self_CheckImgYZM("checkcode", imgyzm) == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "图片验证码错误！", false, ""));
                }
            }
            #endregion

            #region 60秒内禁止重新发送短信
            DateTime? lstime = Session["dxtime"] as DateTime?;
            if (lstime != null)
            {
                if (lstime.Value.AddSeconds(60) > DateTime.Now)
                {
                    string msg = string.Format("短信已发送，{0}秒后可重试", (int)(lstime.Value.AddSeconds(60) - DateTime.Now).TotalSeconds);
                    return Json(CommonHelper.Self_GetRes(-1, msg, false, ""));
                }
            }
            #endregion

            #region 生成随机验证码4位数字
            string yzm = "";
            Random rd = new Random();
            for (int i = 0; i < 4; i++)
            {
                yzm += rd.Next(0, 10);
            }
            Session["dxyzm"] = yzm;
            Session["dxtime"] = DateTime.Now;
            Session["dxphone"] = name;
            #endregion

            return Json(CommonHelper.Self_GetRes(1, "发送成功！" + yzm, false, ""));
        }

        //注册页面
        public ActionResult ZhuCeView()
        {
            DTO_jiudian modeljd = new DTO_jiudian();
            string imginit = "../../image/icon_zc.jpg";
            modeljd.img_yingye_zhizhao = imginit;
            modeljd.img_faren_shenfenzheng_fan = imginit;
            modeljd.img_faren_shenfenzheng_zheng = imginit;
            modeljd.img_shenqingren_sfz_fan = imginit;
            modeljd.img_shenqingren_sfz_zheng = imginit;
            modeljd.img_tezhong_hangye = imginit;
            ViewBag.modeljdstr = JsonConvert.SerializeObject(new DTO_jiudian());
            //图片验证码，调用同一个发送短信的方法时验证用
            Session["checkcode"] = "0000";
            return View();
        }

        //图片上传
        public ActionResult ImgUpload()
        {
            #region 存放方法变量

            //存放分配的数据库图片名称
            List<string> lisImgName = new List<string>();
            //存放成功的数据库图片名称
            List<string> lisImgOK = new List<string>();
            //存放失败的图片的原始文件名称
            List<string> lisImgFail = new List<string>();
            #endregion

            #region 获取上传的文件的对象
            int filecount = Request.Files.Count;
            if (filecount <= 0)
                return Json(CommonHelper.Self_GetRes(-1, "请选择上传的文件！", false, ""));
            //分配数据库图片名称
            lisImgName = new BillCodeHelper().GetGUID(filecount);
            //一张一张的上传
            for (int i = 0; i < filecount; i++)
            {
                var img = Request.Files[i];
                string photoName = lisImgName[i] + img.FileName.Substring(img.FileName.LastIndexOf('.'));
                string resUpload = OSSHelper.Oss_UploadObject(photoName, img);
                if (resUpload != null)
                {
                    lisImgOK.Add(photoName);
                }
                else
                {
                    lisImgFail.Add(img.FileName);
                }
            }
            #endregion

            #region 将文件路径保存到数据库
            if (lisImgOK.Count <= 0)
            {
                return Json(CommonHelper.Self_GetRes(-1, "上传失败！", false, ""));
            }
            else
            {
                return Json(CommonHelper.Self_GetRes(1, "上传成功！", false, PublicStaticObject.imgHeader + lisImgOK.First()));
            }

            #endregion


        }

        //获取一个空的酒店结构model
        public ActionResult GetModelJD()
        {
            DTO_jiudian modeljd = new DTO_jiudian();
            string imginit = "../../image/icon_zc.jpg";
            modeljd.img_yingye_zhizhao = imginit;
            modeljd.img_faren_shenfenzheng_fan = imginit;
            modeljd.img_faren_shenfenzheng_zheng = imginit;
            modeljd.img_shenqingren_sfz_fan = imginit;
            modeljd.img_shenqingren_sfz_zheng = imginit;
            modeljd.img_tezhong_hangye = imginit;
            return Json(modeljd);
        }

        //保存注册页面数据
        public ActionResult ZhuCeP()
        {
            string modeljdstr = Request["modeljd"];
            string modelyhstr = Request["modelyh"];

            #region 存放方法变量
            DTO_yonghu_jiudian modelyh_dto = new DTO_yonghu_jiudian();
            modelyh_dto = JsonConvert.DeserializeObject<DTO_yonghu_jiudian>(modelyhstr);
            DTO_jiudian modeljd_dto = new DTO_jiudian();
            modeljd_dto = JsonConvert.DeserializeObject<DTO_jiudian>(modeljdstr);
            //存放默认时间
            DateTime dt2000 = DateTime.Parse("2000-01-01");
            string dt2000str = "2000-01-01";
            DateTime dtnow = DateTime.Now;

            #endregion

            #region 检查数据是否有效
            if (string.IsNullOrEmpty(modelyh_dto.zhanghao))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入电话号码！", false, ""));
            }
            else
            {
                if (Regex.IsMatch(modelyh_dto.zhanghao, @"^1[3456789]\d{9}$") == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "无效电话号码！", false, ""));
                }
                if (Session["dxphone"] != null && string.IsNullOrEmpty(Session["dxphone"].ToString()) == false && Self_CheckImgYZM("dxphone", modelyh_dto.zhanghao) == false)
                {
                    //更换了电话号码，需要重新发送短信
                    Session["dxyzm"] = "";
                    return Json(CommonHelper.Self_GetRes(-1, "请重新发送短信验证码！", false, ""));
                }
            }

            if (string.IsNullOrEmpty(modelyh_dto.yanzhengma))
            {
                return Json(CommonHelper.Self_GetRes(-1, "请输入短信验证码！", false, ""));
            }
            else
            {
                if (Self_CheckImgYZM("dxyzm", modelyh_dto.yanzhengma) == false)
                {
                    return Json(CommonHelper.Self_GetRes(-1, "短信验证码错误！", false, ""));
                }
            }
            #endregion

            #region 酒店字段有效性判断
            string imgKeyWord = "pms-wenlvting";
            if (modeljd_dto.img_yingye_zhizhao.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 营业执照", false, ""));
            }
            if (modeljd_dto.img_faren_shenfenzheng_fan.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 法人身份证反面照", false, ""));
            }
            if (modeljd_dto.img_faren_shenfenzheng_zheng.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 法人身份证正面照", false, ""));
            }
            if (modeljd_dto.img_shenqingren_sfz_fan.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 申请人身份证反面照", false, ""));
            }
            if (modeljd_dto.img_shenqingren_sfz_zheng.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 申请人身份证正面照", false, ""));
            }
            if (modeljd_dto.has_tehang_xukezheng && modeljd_dto.img_tezhong_hangye.Contains(imgKeyWord) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请上传 特种行业证件照", false, ""));
            }
            if (string.IsNullOrEmpty(modeljd_dto.jd_name))
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请填写 旅馆、名宿名称", false, ""));
            }
            if (string.IsNullOrEmpty(modeljd_dto.tongyi_xinyong_daima))
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请填写 统一社会信用代码", false, ""));
            }
            DateTime dt_kaiye_riqi = dt2000;
            if (DateTime.TryParse(modeljd_dto.kaiye_riqi, out dt_kaiye_riqi) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请填写 开业时间", false, ""));
            }
            DateTime dt_pingxing_riqi = dt2000;
            if (modeljd_dto.is_xingji && DateTime.TryParse(modeljd_dto.pingxing_riqi, out dt_pingxing_riqi) == false)
            {
                return Json(CommonHelper.Self_GetRes(-1, "注册失败！请填写 评星时间", false, ""));
            }
            else
            {
                modeljd_dto.pingxing_riqi = dt2000str;
            }
            #endregion

            #region 账号是否存在
            string whereStr = " zhanghao='" + modelyh_dto.zhanghao + "' AND zhuangtai=1 ";
            DTO_Res msg = new DTO_Res();
            //酒店用户
            List<yonghu_jiudian> lisjd = bll.Get_yonghu_jiudian(whereStr);
            if (lisjd != null && lisjd.Count > 0)
            {
                msg = CommonHelper.Self_GetRes(-1, "账号已存在，请直接登录！", false, "");
                return Json(msg);
            }

            //文旅厅用户
            List<yonghu_wenlvting> liswlt = bll.Get_yonghu_wenlvting(whereStr);
            if (lisjd != null && lisjd.Count > 0)
            {
                msg = CommonHelper.Self_GetRes(1, "账号已存在，请直接登录！", false, "");
                return Json(msg);
            }

            #endregion

            #region 酒店是否存在
            whereStr = string.Format("jd_name='{0}' and shenhe_zhuangtai<=1", modeljd_dto.jd_name);
            List<jiudian> lisjiudian = bll.Get_jiudian(whereStr);
            if (lisjiudian != null && lisjiudian.Count > 0)
            {
                msg = CommonHelper.Self_GetRes(-1, "酒店已存在，请直接登录！", false, "");
                return Json(msg);
            }
            #endregion

            #region 酒店其他默认字段
            modeljd_dto.shenhe_zhuangtai = 0;
            modeljd_dto.shenhe_shijian = dt2000str;
            modeljd_dto.yingye_zhuangtai = 0;
            modeljd_dto.yingye_zhuangtai_shijian = dt2000str;
            modeljd_dto.shenqing_shijian = dtnow.ToString("yyyy-MM-dd HH:mm:ss");
            modeljd_dto.suoshu_pinpai_guojia = modeljd_dto.suoshu_pinpai_guojia == null ? "" : modeljd_dto.suoshu_pinpai_guojia;
            modeljd_dto.chuanzhen = modeljd_dto.chuanzhen == null ? "" : modeljd_dto.chuanzhen;
            modeljd_dto.shenhe_jujue_shuoming = modeljd_dto.shenhe_jujue_shuoming == null ? "" : modeljd_dto.shenhe_jujue_shuoming;
            modeljd_dto.yingye_zhuangtai_shuoming = modeljd_dto.yingye_zhuangtai_shuoming == null ? "" : modeljd_dto.yingye_zhuangtai_shuoming;
            #endregion

            #region 转换数据
            jiudian modeljd = new jiudian();
            modeljd = JsonConvert.DeserializeObject<jiudian>(JsonConvert.SerializeObject(modeljd_dto));
            yonghu_jiudian modelyh = new yonghu_jiudian();
            modelyh.jdid_json = "[]";
            modelyh.leixing = 1;
            modelyh.xingming = modelyh_dto.xingming;
            modelyh.zhanghao = modelyh_dto.zhanghao;
            modelyh.zhuangtai = 1;
            #endregion

            #region 用户和酒店的关联标志
            modelyh.guid_jdyh = new Guid().ToString();
            modeljd.guid_jdyh = modelyh.guid_jdyh;

            #endregion

            #region 将数据写入数据库中
            int res = bll.Add_ZhuCe(modeljd, modelyh);
            if (res > 0)
            {
                return Json(CommonHelper.Self_GetRes(1, "注册成功！", false, ""));
            }
            else
            {
                return Json(CommonHelper.Self_GetRes(1, "注册失败！", false, ""));
            }
            #endregion


        }

        //获取行政区划数据
        public ActionResult GetArea()
        {
            int parentid = int.Parse(Request["id"].ToString());
            List<t_area> lisarea = new List<t_area>();
            lisarea = bll.Get_t_area(string.Format("parentId={0}", parentid));
            if (lisarea == null)
            {
                lisarea = new List<t_area>();
            }
            return Json(lisarea);

        }



        #region 自定义方法

        /// <summary>
        /// 检查验证码是否一致
        /// </summary>
        /// <param name="sessionName">session中存放的名字</param>
        /// <param name="yzm"></param>
        /// <returns></returns>
        public bool Self_CheckImgYZM(string sessionName, string yzm)
        {
            string sess_yzm = Session[sessionName] as string;
            if (string.IsNullOrEmpty(sess_yzm) || string.IsNullOrEmpty(yzm))
            {
                return false;
            }
            if (sess_yzm.ToLower() != yzm.ToLower())
            {
                return false;
            }
            return true;
        }


        #endregion

    }
}
